import {
    ref,
    computed
} from 'vue'
export default function useEditTodo(todoRef) {

    //当前正在修改的哪一个todo
    const editingTodoRef = ref(null)

    // 保持原来的title值
    let originTitle = null



    // 执行修改
    const editTodo = (todo) => {
        originTitle = todo.title
        editingTodoRef.value = todo
    }

    // 完成修改
    const doneTodo = (todo) => {
        editingTodoRef.value = null
        const title = todo.title.trim()
        if(title){
            todo.title = title
        }else{
            // 删除
            todoRef.value.splice( todoRef.value.indexof(todo),1)
        }
    }

    // 取消修改
    const cancelEdit = (todo) => {
        todo.title = originTitle
        editingTodoRef.value = null
    }

    // 设置全部的状态方法
    const allDoneRef = computed({
            get() {
                return todoRef.value.filter(it => !it.completed).length === 0
            },
            set(checked) {

                todoRef.value.forEach(v => {
                        v.completed = checked

                    }
                )
            }
                
            });

        return {
            editingTodoRef,
            editTodo,
            doneTodo,
            cancelEdit,
            allDoneRef
        }
    }